package cn.longg.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Configuration
@MapperScan("cn.longg.mapper")
@EnableTransactionManagement
@Import(SpringService.class)
public class SpringMybatis {

    @Bean
    public DruidDataSource getDataSource()  {
        InputStream is = SpringMybatis.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        DruidDataSource dataSource = null;
        try {
            properties.load(is);
            dataSource = new DruidDataSource();
            dataSource.configFromPropety(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean getFactory(DruidDataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        tk.mybatis.mapper.session.Configuration configuration = new tk.mybatis.mapper.session.Configuration();
        PageInterceptor pageInterceptor = new PageInterceptor();
        pageInterceptor.setProperties(new Properties());
        sqlSessionFactoryBean.setPlugins(pageInterceptor);
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean;
    }
}
